<?php

class ImageController extends Controller {
    
    public function actionAdd(){
        $result = array(
            'error' => false,
            'message' => '',
            'data' => array()
        );
        if (isset($_POST['Image']) && isset($_POST['id'])) {
            $model = Image::model()->findByPk($_POST['id']);
            if($model == null){
                $model = new Image();
            }
            $model->attributes = $_POST['Image'];
            $file = CUploadedFile::getInstance($model, 'link');
            if ($file != null) {
                $newName = time() . "." . $file->extensionName;
                $model->link = $newName;
            }
            if ($model->save()) {
                if($file != null){
                    $file->saveAs(PATH_IMAGE_PRODUCT . $newName);
                }
                $criteria = new CDbCriteria();
                $criteria->addCondition("product_id=:product_id");
                $criteria->params = array(':product_id' => $model->product_id);
                $images = Image::model()->findAll($criteria,array('order' => 'orders ASC'));
                $result['message'] = $this->renderPartial('add',array('images' => $images),true);
            } else {
                $result['error'] = true;
            }
        }
        
        $this->layout=false;
        header('Content-type: application/json');
        echo CJavaScript::jsonEncode($result);
        Yii::app()->end();
    }
    
    /**
     * remove banner
     */
    public function actionDelete(){
        $is_delete = false;
        if(isset($_GET['id'])){
            $model = Image::model()->findByPk($_GET['id']);
            if($model != null){
                $file = $model->link;
                if(Image::model()->deleteByPk($_GET['id'])){
                    if(file_exists(PATH_IMAGE_PRODUCT.$file)){
                        unlink(PATH_IMAGE_PRODUCT.$file);
                    }
                    $is_delete = true;
                }
            }
        }
        $this->layout=false;
        header('Content-type: application/json');
        echo CJavaScript::jsonEncode(array('is_deleted' => $is_delete));
        Yii::app()->end(); 
    }
}